package com.zhiyiang.service.user;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhiyiang.mapper.UserMapper;
import com.zhiyiang.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
public class UserServiceImpl implements UserService{
    @Autowired
    private UserMapper userMapper;
    @Override
    public Integer dologin(String username,String password) {
        Integer role = 0;
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(StringUtils.hasLength(username),"usercode", username);
        List<User> userList = userMapper.selectList(queryWrapper);
        for (User user : userList) {
            if(user.getPassword().equals(password)){
               role = user.getRole();
            }
        }
        return role;
    }

    @Override
    public Page<User> getAllUser(Integer current,Integer size) {
        Page<User> page = new Page<>(current, size);
        Page<User> userPage = userMapper.selectPage(page, null);
        return userPage;

    }

    @Override
    public Page<User> getUser(String query,Integer current,Integer size) {
        Page<User> page = new Page<>(1, size);
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(StringUtils.hasLength(query),"username", query);
        Page<User> userPage = userMapper.selectPage(page, queryWrapper);
        return userPage;

    }

    @Override
    public Boolean addUser(User user) {
        Boolean flag = false;
        int insert = userMapper.insert(user);
        if (insert>0){
            flag = true;
        }
        return flag;
    }

    @Override
    public User getUser(String usercode) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(StringUtils.hasLength(usercode),"usercode", usercode);
        User user = userMapper.selectOne(queryWrapper);
        return user;
    }

    @Override
    public Boolean updateUser(String usercode, User user) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(StringUtils.hasLength(usercode),"usercode", usercode);
        int update = userMapper.update(user,queryWrapper);
        boolean flag = false;
        if (update>0){
            flag=true;
        }
        return flag;
    }

    @Override
    public Boolean deleteUser(String usercode) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(StringUtils.hasLength(usercode), "usercode", usercode);
        int delete = userMapper.delete(queryWrapper);
        Boolean flag = false;
        if (delete>0){
            flag = true;
        }
        return flag;
    }

}
